class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val?: number, next?: ListNode | null) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}

function reverseList(head: ListNode | null): ListNode | null {
  if (head === null) return null;
  if (head.next === null) return head;

  const stack: ListNode[] = [];

  let current: ListNode | null = head;

  while (current) {
    stack.push(current);
    current = current?.next;
  }

  //出栈
  const newHead: ListNode = stack.pop()!;
  let newHeadCurrent = newHead;
  while (stack.length) {
    const node = stack.pop()!;
    newHeadCurrent.next = node;
    newHeadCurrent = newHeadCurrent.next;
  }
  newHeadCurrent.next = null;

  return newHead;
}

//mock
const node1 = new ListNode(1);
node1.next = new ListNode(2);
node1.next.next = new ListNode(3);

const newHead = reverseList(node1);
console.log(newHead, "///");

let current = newHead;

while (current) {
  console.log(current.val);
  current = current.next;
}
